package cn.infinite.security.provider;

import cn.infinite.security.core.WxAuthenticateAble;
import cn.infinite.security.token.WxAuthAuthenticationToken;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

@Slf4j
@AllArgsConstructor
public class WxCodeAuthenticationProvider implements AuthenticationProvider {


    private WxAuthenticateAble wxAuthenticateAble;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(WxAuthAuthenticationToken.class, authentication, "unsupported authentication type");
        Assert.isTrue(!authentication.isAuthenticated(), "already authenticated");
        WxAuthAuthenticationToken wxAuthAuthenticationToken = (WxAuthAuthenticationToken) authentication;
        //code登录
        UserDetails user = this.wxAuthenticateAble.authenticateByWxCode(wxAuthAuthenticationToken.getCode());
        if (user == null) {
            throw new InternalAuthenticationServiceException("微信code授权登录失败");
        }
        WxAuthAuthenticationToken successWxAuthAuthenticationToken = new WxAuthAuthenticationToken(user, "success",
                user.getAuthorities());
        successWxAuthAuthenticationToken.setDetails(wxAuthAuthenticationToken.getDetails());

        return successWxAuthAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WxAuthAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
